package com.clusterswisdom.horn.api.tmall.formate;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.clusterswisdom.horn.api.ioc.struct.StructConfig;
import com.clusterswisdom.horn.api.ioc.struct.StructFormatter;
import com.clusterswisdom.horn.api.tmall.TmallInstance;
import com.clusterswisdom.horn.api.tmall.util.TmallUtil;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.Order;
import com.taobao.api.domain.PromotionDetail;
import com.taobao.api.domain.Trade;
import com.taobao.api.response.ItemGetResponse;

/**
 * itemTotal  listTotal区别
 * 
 * @author bin
 *
 */
public class TradeFormatter implements StructFormatter {
	
	private Logger log = LoggerFactory.getLogger(TradeFormatter.class);
	
	private static final String ORIGIN_WAP = "WAP";
	
	private static final String ORIGIN_PC = "PC";

	@Override
	public JSONObject format(Object object, StructConfig config) throws Exception {
		if (object == null) {
			return new JSONObject();
		}
		
		Trade trade = (Trade)object;
		double total = getTradeTotal(trade);
		double discount = getTotalPromotionFree(trade);
		
		JSONObject returnObject = new JSONObject();
		returnObject.put("ttradeId", trade.getTid().toString());
		returnObject.put("torderStatus", trade.getStatus());
		returnObject.put("torderTime", trade.getCreated());
		returnObject.put("tireBrand", "M410");
		returnObject.put("total", Double.toString(total));
		returnObject.put("paid", trade.getPayment());
		returnObject.put("discount", Double.toString(discount));
		returnObject.put("listTotal", trade.getTotalFee());
		returnObject.put("alipayNO", trade.getAlipayNo());
		returnObject.put("payTime", trade.getPayTime());
		returnObject.put("customerId", trade.getBuyerNick());
		returnObject.put("customerName", trade.getBuyerNick());
		returnObject.put("customerPhone", trade.getReceiverMobile());
		returnObject.put("customerEmail", trade.getBuyerEmail());
		returnObject.put("origin", getOrigin(trade.getTradeFrom()));
		returnObject.put("orderType", "M250");
		returnObject.put("orderItem", getOrderItem(trade));
		
		return returnObject;
	}
	
	private double getTradeTotal(Trade trade) {
		double total = TmallUtil.getPrice(trade.getTotalFee());
		total -= getTotalPromotionFree(trade);
		if(trade.getPostFee() != null){
			total += Double.parseDouble(trade.getPostFee());
		}
		
		return total;
	}
	
	private double getTradeDiscountFree(Trade trade, double total) {
		return TmallUtil.getPrice(trade.getTotalFee()) - total;
	}
	
	private double getTotalPromotionFree(Trade trade) {
		if (trade == null) {
			return 0.00d;
		}
		
		List<PromotionDetail> promotions = trade.getPromotionDetails();
		if (promotions == null || promotions.size() == 0) {
			return 0.00d;
		}
		
		double free = 0.00d;
		for (PromotionDetail promotionDetail : promotions) {
			free += TmallUtil.getPrice(promotionDetail.getDiscountFee());
		}
		
		return free;
	}
	
	private List<JSONObject> getOrderItem(Trade trade) throws Exception {
		if (trade.getOrders() == null) {
			return null;
		}
		
		List<JSONObject> orderList = new ArrayList<JSONObject>(trade.getOrders().size());
		for (Order order : trade.getOrders()) {
			JSONObject orderJson = new JSONObject();
			orderJson.put("torderId", order.getOid().toString());
			orderJson.put("ttradeId", trade.getTid().toString());
			orderJson.put("torderItemStatus", order.getStatus());
			orderJson.put("torderItemRefundStatus", order.getRefundStatus());
			orderJson.put("orderItemType", "M240");
			orderJson.put("orderContentID", order.getOuterIid());
			orderJson.put("productName", order.getTitle());
			orderJson.put("itemTotal", order.getTotalFee());
			orderJson.put("quantity", order.getNum() == null ? "0" : order.getNum().toString());
			
			log.debug("order.getNumIid() :" + order.getNumIid() + ";" + order.getPrice());
			Item item = getItem(order.getNumIid());
			if (item != null) {
				orderJson.put("itemListPrice", item.getPrice());  // 原价
				orderJson.put("itemDiscountPrice", getDiscountPrice(order, item)); // 现价
				
			} else {
				orderJson.put("itemListPrice", "0.00");  // 原价
				orderJson.put("itemDiscountPrice", "0.00"); // 现价
				
			}
			
			orderList.add(orderJson);
		}
		
		return orderList;
	}
	
	private String getOrigin(String from) {
		if (from == null) {
			return ORIGIN_PC;
		}
		
		return from.indexOf("WAP") == -1 ? ORIGIN_PC : ORIGIN_WAP;
	}
	
	private String getDiscountPrice(Order order, Item item) {
		if (order.getNum() == 0) {
			return item.getPrice();
		}
		
		double iPrice = TmallUtil.getPrice(item.getPrice());
		double oDiscountFee = TmallUtil.getPrice(order.getDiscountFee());
		return Double.toString(iPrice - oDiscountFee / order.getNum());
	}
	
	private Item getItem(Long nummId) throws Exception {
		JSONObject param = new JSONObject();
		param.put("num_iid", nummId);
		
		ItemGetResponse response = (ItemGetResponse)TmallInstance.getInstance().executeRequest(param, "item", "itemGet");
		return response.getItem();
	}
}